package top.yaofengqiao.springcloudsimple.message.biz.domain.sms.service;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import top.yaofengqiao.springcloudsimple.message.biz.domain.sms.model.entity.SmsRecordEntity;
import top.yaofengqiao.springcloudsimple.message.biz.domain.sms.model.req.SendSmsRequest;
import top.yaofengqiao.springcloudsimple.message.biz.domain.sms.model.valobj.SmsStatus;
import top.yaofengqiao.springcloudsimple.message.biz.domain.sms.repository.ISmsRecordRepository;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * @author yfq
 * @date 2024/6/22 10:52
 * @description
 */
@Slf4j
public abstract class AbstractSmsService implements ISmsService {
    @Resource
    private ISmsRecordRepository smsRecordRepository;

    @Override
    public boolean send(SendSmsRequest request) {
        // 1. TODO  验证手机号发送次数是否上线

        // 2. 保存短信发送记录
        SmsRecordEntity smsRecordEntity = SmsRecordEntity.builder()
                .platform(platform().getCode())
                .phone(request.getPhone())
                .content(request.getContent())
                .status(SmsStatus.WAITING.getStatus())
                .createTime(LocalDateTime.now())
                .build();
        long id = smsRecordRepository.saveGetId(smsRecordEntity);
        if (id == -1) {
            log.error("短信记录保存失败：{}", JSON.toJSONString(request));
            return false;
        }

        // 3. 发送短信
        boolean done = doSend(request);

        // 4. 更新发送记录状态
        SmsStatus target = done ? SmsStatus.SENDING : SmsStatus.FAIL;
        boolean changed = smsRecordRepository.changeStatus(id, SmsStatus.WAITING, target);

        if (!changed) log.error("短信记录状态更新失败：{}", JSON.toJSONString(request));

        return done;
    }

    protected abstract boolean doSend(SendSmsRequest request);
}
